import 'package:fish_redux/fish_redux.dart';

import 'action.dart';
import 'state.dart';

Reducer<DraggableImagePickerState> buildReducer() {
  return asReducer(
    <Object, Reducer<DraggableImagePickerState>>{
      DraggableImagePickerAction.action: _onAction,
      DraggableImagePickerAction.onAddPic: _onAddPic,
      DraggableImagePickerAction.onReorderPic: _onReorderPic,
      DraggableImagePickerAction.onDeletePic: _onDeletePic,
    },
  );
}

DraggableImagePickerState _onAction(
    DraggableImagePickerState state, Action action) {
  final DraggableImagePickerState newState = state.clone();
  return newState;
}

DraggableImagePickerState _onAddPic(
    DraggableImagePickerState state, Action action) {
  final DraggableImagePickerState newState = state.clone();
  newState.items.add(action.payload);
  return newState;
}

DraggableImagePickerState _onReorderPic(
    DraggableImagePickerState state, Action action) {
  final DraggableImagePickerState newState = state.clone();
  int oldIndex = action.payload['old'];
  int newIndex = action.payload['index'];
  if (oldIndex < newIndex) {
    newIndex -= 1;
  }
  var child = newState.items.removeAt(oldIndex);
  newState.items.insert(newIndex, child);
  return newState;
}

DraggableImagePickerState _onDeletePic(
    DraggableImagePickerState state, Action action) {
  final DraggableImagePickerState newState = state.clone();
  newState.items.remove(action.payload);
  return newState;
}
